# 多阶段构建 Dockerfile

# ==================== 阶段 1: 构建阶段 ====================
FROM node:18-alpine AS builder

# 设置工作目录
WORKDIR /app

# 安装 pnpm
RUN npm install -g pnpm

# 复制 package.json 和 lock 文件
COPY package.json pnpm-lock.yaml* ./

# 安装依赖
RUN pnpm install --frozen-lockfile

# 复制源代码
COPY . .

# 构建应用（根据环境变量决定构建哪个环境）
# 默认构建生产环境
ARG BUILD_ENV=production
RUN if [ "$BUILD_ENV" = "test" ]; then \
  pnpm run build:test; \
  else \
  pnpm run build:prod; \
  fi

# ==================== 阶段 2: Nginx 运行阶段 ====================
FROM nginx:alpine

# 维护者信息
LABEL maintainer="your-email@example.com"
LABEL description="Vite GitLab CI/CD Demo - Nginx Frontend"

# 删除 Nginx 默认配置
RUN rm /etc/nginx/conf.d/default.conf

# 复制自定义 Nginx 配置
COPY nginx.conf /etc/nginx/conf.d/

# 从构建阶段复制构建产物到 Nginx 目录
COPY --from=builder /app/dist /usr/share/nginx/html

# 创建健康检查文件
RUN echo "OK" > /usr/share/nginx/html/health.txt

# 设置文件权限
RUN chmod -R 755 /usr/share/nginx/html

# 暴露端口
EXPOSE 80

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --quiet --tries=1 --spider http://localhost/health.txt || exit 1

# 启动 Nginx
CMD ["nginx", "-g", "daemon off;"]

